package com.lv.suyiyong.hfrwork.ui

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.ktx.setSafeListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.*

import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.SendCodeBody
import com.lv.service.net.VerifyCodeBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserInfo
import com.lv.service.utils.XmlUtils
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.databinding.ActivityVerifyCodeBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：验证信息
 */
@Route(path = ARoutUtils.VerifyCodeActivity)
class VerifyCodeActivity : BaseActivity<ActivityVerifyCodeBinding>(),
    View.OnClickListener {
    @Autowired(name = "userinfo")
    @JvmField
    var mUserInfo: UserInfo? = null
    private var timer: TimerUnit? = null
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val serviceViewModel: ServiceViewModel by viewModel()

    override fun getLayoutRes() = R.layout.activity_verify_code
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            StatusBarUtil.setHeightAndPadding(this@VerifyCodeActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("验证信息")
            tvCode.setOnClickListener(this@VerifyCodeActivity)
            btnLogin.setSafeListener {
                verifyCode()
            }
        }
    }

    private fun verifyCode() {
        val mCode = mBinding.etCode.text.toString().trim()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.verifyCode(VerifyCodeBody(mUserInfo?.phone!!, mCode))
                }.await()
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                if (code == "200") {
                    timer?.endtTime()
                    timer = null
                    ARouter.getInstance().build(ARoutUtils.UserInfoCollectActivity)
                        .navigation()
                    finish()
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    override fun initConfig() {
        super.initConfig()

        if (mUserInfo != null) {
            val phone = mUserInfo?.phone
            val phoneSub = XmlUtils.parsePhone(phone!!)
            mBinding.tvHint.text = "验证码将发送至手机$phoneSub"
        }

    }


    override fun initData() {
        super.initData()

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_code -> showSwipecaptDialog(mUserInfo!!.phone!!)
        }
    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true, object : OnDialogSureListener {
                override fun onSureClick(content: String?) {
                    val sendCode = YgxUtilsKt.sendCode(phone)
                    startLoading()
                    lifecycleScope.launchWhenCreated {
                        this.launch {
                            val result: DataResult<BaseYgxRsp> =
                                myScope.async {
                                    serviceViewModel.sendCode(
                                        SendCodeBody(
                                            phone,
                                            sendCode
                                        )
                                    )
                                }.await()
                            parseSendCodeResult(result)
                        }
                    }
                }
            })
        swipeCatpchaDialog.show()
    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (code == "200") {
                    if (timer == null) {
                        timer = TimerUnit(mBinding.tvCode)
                    }
                    timer?.startTime()
                    message?.let { message ->
                        showToast(this@VerifyCodeActivity, message)
                    }
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }
}